package com.gopay.scheduler.job;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;

import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.util.DateUtils;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.sms.client.GopaySMSHttpClient;
import com.gopay.sms.common.constants.SMSAppId;
import com.gopay.sms.common.domain.RequestVO;
import com.ibm.icu.math.BigDecimal;

/**
 * 
 * @ClassName: CbRmbIcbcToCcbAmtWarnJob
 * @Description: 跨境人民币 报盘前通知运营人员去拨款  11:15和下午3:45各拨一次款
 * @author qld
 * @date 2017年1月19日 下午4:27:03 ww.gopay.com.cn Inc.All rights reserved.
 */
public class CbRmbIcbcToCcbAmtWarnJob extends GopayBaseJob {
    // 日志
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private @Value("#{webProperties['cbrmbMobile']}") String mobile;

    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;

    @Override
    protected void doJobInternal() {
        /**
         * 现在暂时一天跑2次，11:15的跑上一工作日15：30-当天11：00的所有汇款和提现到境外订单
         * 下午3:45的跑当天11：00-15：30的所有汇款和提现到境外订单中是否有拨款失败或拨款进行中的
         */
        Date now=new Date();
        if (!isHoliday(now)) {
            logger.info("=======start CbRmbIcbcToCcbAmtWarnJob  ===========");
            Calendar c = Calendar.getInstance();
            int year=c.get(Calendar.YEAR);
            int month=c.get(Calendar.MONTH)+1;
            int day=c.get(Calendar.DATE);
            int hour = c.get(Calendar.HOUR_OF_DAY);
            int minute = c.get(Calendar.MINUTE);
            Date nowTime = c.getTime();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date date11 = new Date(nowTime.getYear(), nowTime.getMonth(), nowTime.getDate(), 11, 00);
            Date date330 = new Date(nowTime.getYear(), nowTime.getMonth(), nowTime.getDate(), 15, 30);
            // String hql = "from CbRmbTranAssistDtl where state=:state";
            // 已经发生退款的汇款类订单不要去拨款了,edit by qld 20160810
            // 在20161109再次修改逻辑，汇款充值的reid=汇款的订单号，汇款充值退款的reid=汇款充值的，所以2个关联获取该笔汇款订单是否发生退款
            // cb_rmb_force_refund_record表的is_refund 0--成功，1--进行中 2--失败
            String sql = "select sum(m.mer_txn_amt),count(1),'' from cps_gen_main_order m,cps_gen_pay_order p where  m.gopay_order_id=p.gopay_order_id " +
            		" and p.pay_stat in ('02','05') and m.gopay_int_txn_cd='01734' and not exists(select 1 from cps_gen_main_order t,cb_rmb_force_refund_record f " +
            		" where m.relevance_gopay_order_id=t.gopay_order_id  and t.gopay_order_id=f.gopay_order_id and f.refund_status!='20003')" +
            				" and  m.gopay_txn_tm<=to_date(:stime,'yyyy-MM-dd hh24:mi:ss')  ";
            Map<String, Object> param = new HashMap<String, Object>();
            if (hour == 11 && minute == 15) {// 11:15的
                param.put("stime", sdf.format(date11));
                List<Object[]> list = commonQueryDAO.findBySql(sql, param);
                if (list != null && list.get(0) != null) {
                    String sum = list.get(0)[1].toString();
                    if ("0".equals(sum)) {
                        // 说明没有数量要发送，不用干活
                    } else {
                        BigDecimal totalAmt = new BigDecimal(list.get(0)[0].toString());

                        if (totalAmt.compareTo(BigDecimal.ZERO) > 0) {
                            sendSmsNotify(year + "年" + month + "月" + day + "日11:00之前有" + sum + "笔拨款未成功的订单，共计" + totalAmt
                                    + "元，烦请进行线下处理");
                        }
                        logger.info("跨境拨款总金额:" + totalAmt);
                    }
                }

            } else if (hour == 15 && minute == 45) {// 3:45
                param.put("stime", sdf.format(date330));
                List<Object[]> list = commonQueryDAO.findBySql(sql, param);
                if (list != null && list.get(0) != null) {
                    String sum = list.get(0)[1].toString();
                    if ("0".equals(sum)) {
                        // 说明没有数量要发送，不用干活
                    } else {
                        BigDecimal totalAmt = new BigDecimal(list.get(0)[0].toString());

                        logger.info("跨境拨款总金额:" + totalAmt);
                        if (totalAmt.compareTo(BigDecimal.ZERO) > 0) {
                            sendSmsNotify(year + "年" + month + "月" + day + "日15:30之前有" + sum + "笔拨款未成功的订单，共计" + totalAmt
                                    + "元，烦请进行线下处理");
                        }
                    }
                }
            }else{
                logger.info("这个时间不跑定时任务去报盘");
            }

        } else {
            logger.info(" ======= 非工作时间，抱歉哦！ ===========");

        }
    }


    /**
     * 发送短信
     * 
     * @param mobileNo
     * @param smsType
     * @return
     */
    private void sendSmsNotify(String content){
        try {
            RequestVO req = new RequestVO();
            req.setAppId(SMSAppId._90000.value);
            req.setMobile(mobile);//如果发送多个手机号码时，可使用逗号进行隔开。
            req.setContent(content);
            GopaySMSHttpClient.getInstance().createVerificationCode(req);
        } catch (Exception e) {
           // e.printStackTrace();
            logger.error("发送短信通知时异常", e);
        }
    }
    
    /**
     * 是否为节假日,暂时就用节假日表01类型
     * @return
     */
    public boolean isHoliday(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        String year = DateUtils.format(calendar.getTime(), "yyyy");
        String month = DateUtils.format(calendar.getTime(), "M");
        String day = DateUtils.format(calendar.getTime(), "d");
        
        StringBuilder sb = new StringBuilder();
        
        sb.append(" select t.year, t.month, t.holidays ");
        sb.append("   from holiday_information t ");
        sb.append("  where 1 = 1       ");
        sb.append("    and ','||t.holidays||',' like :holidays ");
        sb.append("    and t.month=:month ");
        sb.append("    and t.year=:year ");
        sb.append("    and t.holiday_type = '01' ");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("holidays", "%,"+day+",%");
        map.put("month", month);
        map.put("year", year);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);

        return rsList != null && rsList.size() > 0;
    }
}
